package com.example.jdcompetition.Service.cvsPro.jd;

import com.example.jdcompetition.Service.cvsPro.time.TransitTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.example.jdcompetition.JdcompetitionApplication.transit;

/**
 * @author henrydai
 * @date 2021/6/19 16:04
 */
@Service
@Slf4j
public class ExeTransit {
    public long execute(String[] ori, String[] des, long orderDate) {
        int x=2,y=4; //2-4级
        String OriginateAddress = ori[0]+ori[1];
        String DestinationAddress = des[0]+des[1]+des[2]+des[3];
        while(x>0&&y>0)
        {
            //1根据始发省市查map
            HashMap<String, LinkedList<TransitTime>> transitMap = transit.get(OriginateAddress);
            if(transitMap!=null)
            {
                LinkedList<TransitTime> transitList = transitMap.get(DestinationAddress);
                if(transitList!=null)
                {
                    Collections.sort(transitList);
                    TransitTime tt = getTransitTime(orderDate,transitList);
                    if(tt!=null)
                    {
                        return tt.transitTime;
                    }
                }
            }
            else
            {
                y=1;
            }
            //区别:x,y必须大于0
            if(y>1)
                y--;
            else
            {
                x--;
                y=4;
            }
            if(x<=0)
            {
                log.error("没有合适的中转线路");
                return -1;
            }
            OriginateAddress="";
            DestinationAddress="";
            for(int i=0;i<x;i++)
            {
                OriginateAddress+=ori[i];
            }
            for(int i=0;i<y;i++)
            {
                DestinationAddress+=des[i];
            }
        }
        return -1;
    }

    private TransitTime getTransitTime(long orderDate, LinkedList<TransitTime> transitList)
    {
        int low=0;
        int high=transitList.size()-1;
        int mid;
        while(low<high)
        {
            mid=(low+high+1)/2;
            if(transitList.get(mid).effectiveDate>orderDate)
            {
                high=mid-1;
            }
            else
            {
                low=mid;
            }
        }
        TransitTime temp = transitList.get(low);
        //考虑当天揽收时间

        if(temp.effectiveDate>orderDate || orderDate>temp.expirationDate)
            return null;
        else
            return temp;
    }




}
